﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;
using System.Globalization;

namespace MultilingualInSpaInMvc
{
    public class BaseController : Controller
    {
        protected override void ExecuteCore()
        {
            if (this.RouteData.Values[Constants.ROUTE_PARAMNAME_LANG] != null &&
                 !string.IsNullOrWhiteSpace(this.RouteData.Values[Constants.ROUTE_PARAMNAME_LANG].ToString()))
            {
                // set the culture from the route data (url)
                var lang = this.RouteData.Values[Constants.ROUTE_PARAMNAME_LANG].ToString();
                if(lang == "en-US" || lang == "es" || lang=="en")
                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
            }
            else
            {
                // load the culture info from the cookie
                var cookie = this.HttpContext.Request.Cookies[Constants.COOKIE_NAME];
                var langHeader = string.Empty;
                if (cookie != null)
                {
                    // set the culture by the cookie content
                    langHeader = cookie.Value;
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
                }
                else
                {
                    // set the culture by the location if not speicified
                    langHeader = this.HttpContext.Request.UserLanguages[0];
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
                }
                // set the lang value into route data
                this.RouteData.Values[Constants.ROUTE_PARAMNAME_LANG] = langHeader;
            }

            // save the location into cookie
            //HttpCookie _cookie = new HttpCookie(Constants.COOKIE_NAME, Thread.CurrentThread.CurrentUICulture.Name);
            //_cookie.Expires = DateTime.Now.AddYears(1);
            //this.HttpContext.Response.SetCookie(_cookie);

            base.ExecuteCore();
        }
    }
}